#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <iostream>
#include <string>

#include <cstring>

enum
{
    MSSIZE = 1024,
};

int main(int args, char *argv[])
{
    if (args != 3)
    {
        std::cerr << "Usage:" << argv[0] << "Server ip" << "Server port" << std::endl;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //1.创建tcp套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cerr<<"socket create fail!"<<std::endl;
        exit(1);
    }

    //2.不需要显示的bind，但是客户端一定有自己的IP和Port,
    //也就是需要隐式的bind,OS会用自己的IP和随机端口实现隐式的bind
    
    //3.connect完成后server的accept会返回
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET,serverip.c_str(),&server.sin_addr);
    
    int n = connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n < 0)
    {
        std::cerr<<"connect fail"<<std::endl;
        exit(2);
    }

    //到这里，说明连接成功
    while(true)
    {
        std::string message;
        std::cout<<"Plase Enter#";
        std::getline(std::cin,message);

        write(sockfd,message.c_str(),message.size());

        char echo_buf[MSSIZE] = {0};
        int n = read(sockfd,echo_buf,sizeof(echo_buf));
        if(n > 0)
        {
            echo_buf[n] = '\0';
            std::cout<<echo_buf<<std::endl;
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}